package com.strongbj.iot.devices.hr.response.handle;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.hr.message.HRMessage;
import com.strongbj.iot.devices.hr.message.MQMessageOfHR;
import com.strongbj.iot.devices.hr.response.entity.HRResetResponseEntity;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 门禁心跳包处理类
 * 
 * @author Pingfan
 *
 */
public class HRResetResponseHandle implements IMessageHandle<HRMessage, Object> {
	protected static Logger logger = LogManager.getLogger(HRResetResponseHandle.class.getName());
	protected TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	protected static final String ACTION_CODE = "collect013";
	
	public HRResetResponseHandle(String doorDirection) {
		super();
	}
	
	@Override
	public boolean isHandle(HRMessage t) {
		if (t.getCommand() == 0x0D) { // 重启反馈命令类型为0x0D
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, HRMessage t) {
		// 取门禁ip
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String ip = insocket.getAddress().getHostAddress();
		
		// 发送重启反馈到MQ, 资产监听
		MQMessageOfHR msg = new MQMessageOfHR();
		msg.setActioncode(ACTION_CODE);
		HRResetResponseEntity resetRsp = new HRResetResponseEntity();
		resetRsp.setDevIp(ip);
		resetRsp.setCommand(t.getCommand());
		if(t.getData()[0] == (byte)0x00) { // data段0x00表示重启成功, 0x80表示失败
			resetRsp.setResetSuccess(true);
		} else {
			resetRsp.setResetSuccess(false);
		}
		msg.setAwsPostdata(resetRsp);
		String json = JSON.toJSONString(msg);
		topicSender.send("hrReader", json);
		logger.info("HR设备发送【重启反馈】成功! topic=hrReader, ip={}, 数据={}", ip, json);
		return null;
	}
}
